package com.hcss.core.common.permissions.dao;

import java.util.Date;
import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.hcss.core.common.permissions.model.UserInfo;
import com.hcss.core.mvc.BaseDao;
import com.hcss.core.mvc.page.Pager;
import com.hcss.core.util.StringUtils;
import com.hcss.core.util.SysDictionary;



/**
 * 用户信息管理Dao
 * @author lvfang
 * @version 1.0
 * @since 1.0
 */
@Repository("userInfoDao")
public class UserInfoDao extends BaseDao {

    /**
     * 保存用户
     * 
     * @param user 输入参数
     */
    public int addUserInfo(final UserInfo user) throws Exception {
        final StringBuffer sql = new StringBuffer();
        sql.append("INSERT INTO ");
        sql.append("t_userInfo (userPwd,userStatus,userName,realName,udesc,itCode,productLine,clOwner,lastNodeId,isDeleted,regTime,lastUnLockTime)");
        sql.append(" VALUES ( ?, ?, ?, ? ,?, ?, ?, ?,?,?,?,?)");
        Object[] params = new Object[]{
        };
        return this.insertSelective(sql.toString(), params);
    }

    /**
     * 修改用户
     * 
     * @param user 输入参数
     */
    public int updateUserInfo(UserInfo user) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("UPDATE ");
        sql.append("t_UserInfo SET userName=?, userStatus=?,realName=?,udesc=?,itCode=?,productLine=?,clOwner=? WHERE id=?");
        Object[] params = new Object[] {};
        return jdbcTemplate.update(sql.toString(), params);
    }
    
    /**
     * 修改用户
     * 
     * @param user 输入参数
     */
    public int updateUserNameInfo(UserInfo user) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("UPDATE ");
        sql.append("t_UserInfo SET realName=?,userMail=? WHERE id=?");
        Object[] params = new Object[] { };
        return jdbcTemplate.update(sql.toString(), params);
    }
    
    /**
     * 修改用户登录地址
     * 
     * @param user 输入参数
     */
    public int updateUserInfoOpUrl(String url,int userId,int lastNodeId) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("UPDATE ");
        sql.append("t_UserInfo SET lastOpUrl=?,lastNodeId=? where id = ?");
        Object[] params = new Object[] {url,lastNodeId,userId};
        return jdbcTemplate.update(sql.toString(), params);
    }
    /**
     * <p>
     * 密码重置
     * </p>
     * 
     * @param user
     * @return int 设定文件
     */
    public int resetUserPwd(UserInfo user) {
        StringBuffer sql = new StringBuffer();
        sql.append("UPDATE ");
        sql.append("t_UserInfo SET userPwd=? WHERE id=?");
        Object[] params = new Object[] { user.getUserPwd(), user.getId(), };
        return jdbcTemplate.update(sql.toString(), params);
    }

    /**
     * 删除用户,将status状态修改为锁定
     * 
     * @param user 输入参数
     */
    public int deleteUserInfo(String uids) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("UPDATE t_UserInfo SET userStatus='").append(SysDictionary.USER_STATUS_LOCK);
        sql.append("',isDeleted='y' WHERE id in (").append(uids).append(")");
        return jdbcTemplate.update(sql.toString());
    }

    /**
     * 返回所有用户信息
     * 
     * @return
     */
    public Pager getAllUsers(Pager page, UserInfo user) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT u.*,pl.proName productName FROM T_UserInfo u left join t_productLine pl on pl.id = u.productLine  ");
        sql.append(" where u.id<>0 and u.isDeleted='n' ");
        if (StringUtils.isNotEmpty(user.getUserName())) {
            sql.append(" And u.userName like '%" + user.getUserName() + "%' ");
        }
        if (StringUtils.isNotEmpty(user.getUserStatus())) {
            sql.append(" And u.userStatus ='" + user.getUserStatus() + "' ");
        }

        RowMapper<?> rowMapper = new BeanPropertyRowMapper<UserInfo>(UserInfo.class);
        return this.getPageList(sql.toString(), page, rowMapper);
    }
  
    /**
     * 用户解锁
     * 
     * @param ids 解锁ids
     * @return
     */
    public int unlock(String ids) throws Exception {
        int state = 0;
        StringBuffer sql = new StringBuffer();
        sql.append("UPDATE T_UserInfo SET userStatus ='").append(SysDictionary.USER_STATUS_NORMAL);
        sql.append("'  WHERE id =? ");
        String idArray[] = ids.split(",");
        if (idArray != null) {
            for (int i = 0; i < idArray.length; i++) {
                Object[] params = new Object[] { idArray[i] };
                state = jdbcTemplate.update(sql.toString(), params);
            }
        }
        return state;
    }
    /**
     * 用户解锁 90时天后
     * 
     * @param ids 解锁ids
     * @return
     */
    public int unlockAndRegTime(int id) throws Exception {
        int state = 0;
        StringBuffer sql = new StringBuffer();
        sql.append("UPDATE T_UserInfo SET userStatus ='").append(SysDictionary.USER_STATUS_LOCK);
        sql.append("' ,lastUnLockTime=? WHERE id =? ");
        Object[] params = new Object[] { new Date(),id };
        state = jdbcTemplate.update(sql.toString(), params);
        return state;
    }
    /**
     * 用户锁定
     * 
     * @param ids 解锁ids
     * @return
     */
    public int lock(String ids) throws Exception {
        int state = 0;
        StringBuffer sql = new StringBuffer();
        sql.append("UPDATE T_UserInfo SET userStatus ='").append(SysDictionary.USER_STATUS_LOCK);
        sql.append("'  WHERE id =? ");
        String idArray[] = ids.split(",");
        if (idArray != null) {
            for (int i = 0; i < idArray.length; i++) {
                Object[] params = new Object[] { idArray[i] };
                state = jdbcTemplate.update(sql.toString(), params);
            }
        }
        return state;
    }

    /**
     * 密码重置
     * 
     * @param ids 用户ids
     * @param pwd 加密后密码
     * @return
     */
    public int resetPwd(String id, String pwd) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("UPDATE T_UserInfo SET userPwd ='").append(pwd);
        sql.append("'  WHERE id =").append(id);
        return jdbcTemplate.update(sql.toString());
    }

    /**
     * <p>
     * findById TODO 获取 用户 信息
     * </p>
     * 
     * @param userId
     * @return UserInfo 设定文件
     */
    @SuppressWarnings("unchecked")
	public UserInfo findById(String userId) {
        RowMapper<?> rowMapper = new BeanPropertyRowMapper<UserInfo>(UserInfo.class);
        String sql = "SELECT u.* FROM t_userinfo u WHERE u.id = ? and u.isDeleted = 'n'";
        List<UserInfo> list = (List<UserInfo>) jdbcTemplate.query(sql, new String[] { userId }, rowMapper);
        return list.size() > 0 ? (UserInfo) list.get(0) : null;
    }
    
    /**
     * @Title: findUserNameIsExist
     * <p>验证用户名是否存在<p>
     * @param userName
     * @param userId
     * @return
     * @return: int
     */
    @SuppressWarnings("deprecation")
	public int findUserNameIsExist(String userName,int userId){
    	StringBuffer sql = new StringBuffer("select count(1) from t_userinfo where userName = ?");
    	if(userId != 0){
    		sql.append(" and id <> "+userId);
    	}
    	return this.jdbcTemplate.queryForInt(sql.toString(),userName);
    }
	
	 /**
     * 根据登录用户名密码查询用户信息
     * 
     * @param userInfo
     * @return UserInfo
     * @throws Exception
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public UserInfo getUserInfoByuserNoAndpwd(UserInfo userInfo) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT * FROM t_userInfo  ");
        sql.append(" WHERE isDeleted = 'n' and userNo='").append(userInfo.getUserNo()).append("' AND userPwd='").append(userInfo.getUserPwd()).append("'");
        return (UserInfo) jdbcTemplate.queryForObject(sql.toString(), new BeanPropertyRowMapper(UserInfo.class));
    }

    /**
     * 根据id获取用户信息
     * 
     * @param id
     * @return UserInfo
     * @throws Exception
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public UserInfo getUserInfoById(String id) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT * FROM ").append(" t_userInfo ").append(" WHERE isDeleted = 'n' and  id =").append(id);
        return (UserInfo) jdbcTemplate.queryForObject(sql.toString(), new BeanPropertyRowMapper(UserInfo.class));
    }
    /**
     * 根据用户名密码查询登录用户是否正确
     * 
     * @param model
     */
    @SuppressWarnings({ "unchecked" })
	public int queryUserId(UserInfo userInfo) throws Exception {
        StringBuffer sql = new StringBuffer();
//**********************sql ---sessionFactory 
//        sql.append("SELECT * FROM ").append(" t_userInfo").append(" WHERE isDeleted = 'n' and  userNo= '"+userInfo.getUserNo()+
//        		"' AND userPwd='"+userInfo.getUserPwd()+"' and userStatus <> 'locked'");
//        List<UserInfo> userList = (List<UserInfo>) getHibernateSession().createSQLQuery(sql.toString()).list();
//        if(userList != null && userList.size() > 0){
//        	return 1;
//        }
//        return 0;
        
//**********************sql ---jdbcTemplate       
//		  Object[] params = new Object[] { userInfo.getUserNo(), userInfo.getUserPwd() };
//		  return jdbcTemplate.queryForInt(sql.toString(), params);
        
        
//**********************hql ---hibernateTemplate
        sql.append("FROM ").append(" t_userInfo").append(" WHERE isDeleted = 'n' and  userNo= '"+userInfo.getUserNo()+
        		"' AND userPwd='"+userInfo.getUserPwd()+"' and userStatus <> 'locked'");
        List<UserInfo> userList = (List<UserInfo>) this.hibernateTemplate.find(sql.toString());
        if(userList != null && userList.size() > 0){
        	return 1;
        }
        return 0;
    }
}
